<?php

define('MYSQL_RESULT_TYPE',1);
class apiControl extends Control{
	/*
	 * 构造方法
	 */
	public function __construct(){

		$model = Model();
		$valid = $model->table('wxaccount')->where(array('wx_id'=>1))->find();
		if($valid['wx_is_verify']!='1'){
			$this->valid($valid['wx_token']);
		}
	}
	

	
	/*
	 * 验证接入成功
	 */
	private function valid($wx_token){
		
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$echoStr = $_GET["echostr"];
		
		$token = $wx_token;
		$tmpArr = array($token, $timestamp, $nonce);
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			$model = Model();
			$res = $model->table('wxaccount')->where(array('wx_token'=>$wx_token))->update(array('wx_is_verify'=>1));//1.接入成功
			if($res){
				echo $echoStr;
			}					
			exit;
		}else{
			return false;
		}
	}

	
	
	/*
	 * 接受消息
	 */
	public function responsemsgOp(){
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if(!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$postObj = (array)$postObj;

			$this->fromUsername = $postObj['FromUserName'];	//发送方帐号（一个OpenID） 
            $this->toUsername = $postObj['ToUserName'];	//开发者微信号 
            $createtime = $postObj['CreateTime'];	//消息创建时间
            $content = trim($postObj['Content']);	//文本消息内容 

            //消息类型
            $msgtype = trim($postObj['MsgType']);

			if($msgtype == 'event'){//事件流程
				$event = trim($postObj['Event']);
				switch($event){
					case 'CLICK'://自定义菜单点击
						$this->event_click($postObj['EventKey']);
						break;

					case 'subscribe'://关注账号
						$this->event_subscribe();
						break;
					
					case 'unsubscribe'://取消关注账号
						$this->event_unsubscribe();
						break;	
						
					//case 'LOCATION'://地理位置
					//	$this->event_location();
					//	break;

				}
			}elseif($msgtype == 'text'){//接受普通消息
				$this->text_msg($content);
				//$this->text_msg($this->fromUsername);
			}elseif($msgtype == 'voice'){//接受语音
				
			}
		}

	}
	
	//自定义菜单点击
	private function event_click($key){
		
		if($key == 'client'){
			$textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
						</xml>";
			
			$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, time(), "transfer_customer_service");
			echo $resultStr;die;
		}
		
		$model = Model();
		$menu = $model->table('menu')->where(array('menu_key'=>$key))->find();
		
		if(!empty($menu)){
			$keyword = $model->table('keyword')->where(array('id'=>$menu['menu_act']))->find();
			if($keyword['huifutype']==1){
				$tuwen = $model->table('tuwen')->where(array('id'=>$keyword['huifucontent']))->select();
				$this->image_response_msg($tuwen);
			}else{
				$this->text_response_msg($keyword['huifucontent']);
			}
		}
		
		exit;
		
	}
	
	//关注账号
	private function event_subscribe(){

		$model = Model();
		$guanzhu = $model->table('setting')->where(array('name'=>'weixin_guanzhu'))->find();
		$text = $model->table('setting')->where(array('name'=>'weixin_guanzhu_con'))->find();
		
		$openid = $this->fromUsername;
		$user = $model->table('user')->where(array('openid'=>$openid))->find();
		if(!empty($user)){
			$data = $this->getUserInfo($openid);
			$data['subscribe'] = 1;
			$model->table('user')->where(array('openid'=>$openid))->update($data);
		}else{
			$data = array();
			$data['openid'] = $openid;

			$d = $this->getUserInfo($openid);
			$data = array_merge($data,$d);
			$data['subscribe'] = 1;
			$model->table('user')->insert($data);
		}
		
		
		if($guanzhu['value']=='1'){
			$this->image_response_msg($text['value']);				
		}else{	
			$this->text_response_msg($text['value']);
		}
		
	}

	
	//取消关注账号
	private function event_unsubscribe(){
		$openid = $this->fromUsername;
		$model = Model();
		$model->table('user')->where(array('openid'=>$openid))->update(array('subscribe'=>0));
	}

	//地理位置
	private function event_location(){
		
	}
	
	//接受消息
	private function text_msg($content){
		
		$model = Model();
		$condition = array();
		$condition['keyword'] = array('like',"%{$content}%");
		$keyword = $model->table('keyword')->where($condition)->find();
		
		if(empty($keyword)){
			exit;
		}
		
		if($keyword['keytype']==1){
			if($keyword['keyword']!=$content){
				die;
			}
		}
		
		if($keyword['huifutype']==1){
			$list = $model->table('tuwen')->where(array('id'=>$keyword['huifucontent']))->select();			
			$this->image_response_msg($list);
		}else{
			$this->text_response_msg($keyword['huifucontent']);
		}
		
		
		exit;
		if($content == 'upload'){
			$this->upload();
		}elseif($content == 'download'){
			$this->download();
		}elseif($content == 'openid'){
			//$this->text_response_msg('openid是：'.$this->toUsername);
			$this->text_response_msg('openid是：'.$this->fromUsername);
		}elseif($content == 'tuisong'){
			$this->tuisong();
		}elseif($content == 'qunfa'){
			$this->qunfa();
		}elseif($content == 'view'){
			$content = "<a href='".BASE_SITE_URL."/index.php?act=api&op=share'>点击查看</a>";
			$this->text_response_msg($content);
		}elseif($content == 'home'){
			
			$model = Model();
			$wxaccount = $model->table('wxaccount')->where(array('wx_id'=>1))->find();
			$return_url = BASE_SITE_URL.'/index.php?act=oauth&op=getcode';
			$return_url = urlencode($return_url);
			$url = '<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wxaccount['wx_appid'];
			$url.='&redirect_uri='.$return_url.'&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect">点击这里体验</a>';
			$this->text_response_msg($url);
		}elseif($content == 'client'){
			$textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
						</xml>";
			
			$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, time(), "transfer_customer_service");
			echo $resultStr;die;
		}else{
			$this->text_response_msg($content);
		}
	}
	
	private function qunfa(){
		$data = array();
		$data['touser'] = array('ou9WwvxUTsFqhQtMpogFqrDSmSdk','ou9Wwv4aLLd6X7gK0GPyf9UcgJn0');
		$data['mpnews'] = array('media_id'=>'dTj0ANTvLbHJ7965aMELld4iZzP5LX2FSyags1xEkBI6DWEZX43pkWI-XeiBzCLw');
		$data['msgtype']= 'mpnews';
		$access_token = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={$access_token}";
		$output = $this->https_request($url,$data);
		$output = json_decode($output,true);
		$this->text_response_msg($output['errmsg']);
	}
	
	private function tuisong(){
		
		$access_token = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=$access_token";
		//$this->text_response_msg($url);
		$data = array();
		$data['articles'] = array(
									array(
											'thumb_media_id'=>'QkC9pGFDwyoWnz-DFBGuV0zFVkBaPaFV2ubmm-CXiMElygq0lV9-ldTEC8hCf1-v',
											'author'=>'xxx',
											'title'=>'happy day',
											'content_source_url'=>'www.offlinemall.com',
											'content'=>'content',
											'digest'=>'digest'
										)			
							);
		
		$data = json_encode($data);
		$output = $this->https_request($url,$data);
		$output = json_decode($output,true);
		$this->text_response_msg($output['media_id']);
	}
	
	private function text_response_msg($text){
		$textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>	
		</xml>";

		$resultStr = sprintf($textTpl, $this->fromUsername, $this->toUsername, time(), "text", $text);
		echo $resultStr;die;
	}

	
	private function image_response_msg($newsArray){
		
		if(!is_array($newsArray)){
			return;
		}
		
		$itemTpl = "<item>
				        <Title><![CDATA[%s]]></Title>
				        <Description><![CDATA[%s]]></Description>
				        <PicUrl><![CDATA[%s]]></PicUrl>
				        <Url><![CDATA[%s]]></Url>
				    </item>
					";
		
		$item_str = "";
		foreach ($newsArray as $item){
			$title = $item['tuwen_title'];
			$description = $item['tuwen_shortintro'];
			$picurl = UPLOAD_SITE_URL.'/shop/tuwen/'.$item['tuwen_pic'];
			if(!empty($item['tuwen_url'])){
				$url = $item['tuwen_url'];
			}else{
				$url = BASE_SITE_URL.'/index.php?act=wap&op=article&type=tuwen&article_id='.$item['id'];
			}
			
			$item_str .= sprintf($itemTpl, $title, $description, $picurl, $url);
		}
		
        $xmlTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[news]]></MsgType>
						<ArticleCount><![CDATA[%s]]></ArticleCount>
						<Articles>
						$item_str</Articles>
					</xml>";

        $result = sprintf($xmlTpl,$this->fromUsername, $this->toUsername,time(),count($newsArray));
        echo $result;die;
	}	
}